package com.dragon.english_practice_back.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.dragon.english_practice_back.entity.Session;
import com.dragon.english_practice_back.mapper.MessageMapper;
import com.dragon.english_practice_back.mapper.SessionMapper;
import com.dragon.english_practice_back.service.MessageService;
import com.dragon.english_practice_back.service.ResponseAnalysisService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@AllArgsConstructor
public class MyChatMemory implements ChatMemory {
    SessionMapper sessionMapper;
    MessageMapper messageMapper;
    MessageService messageService;
    ResponseAnalysisService responseAnalysisService;
    @Override
    public void add(String conversationId, List<Message> messages) {
        // 获取session的创建者id
        Session session = sessionMapper.selectById(conversationId);
        if (session == null) {
            log.error("sessionId: {}, This session does not exist ", conversationId);
            return;
        }
        int creatorId = session.getCreatorId();

        com.dragon.english_practice_back.entity.Message saveMessage = new com.dragon.english_practice_back.entity.Message();
        saveMessage.setSessionId(Integer.parseInt(conversationId));
        saveMessage.setCreatorId(creatorId);
        // 设置创建时间
        // 获取当前系统时间，精确到6位微秒
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
        String formattedDateTime = now.format(formatter);

        // 将格式化的时间字符串转换为Date对象
        Date currentDate = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
            currentDate = sdf.parse(formattedDateTime);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        saveMessage.setCreateDate(currentDate);

        saveMessage.setType(messages.get(0).getMessageType().getValue());
        saveMessage.setContent(messages.get(0).getText());

        if (StrUtil.isNotEmpty(saveMessage.getContent()) && messageMapper.insert(saveMessage)>0) {
            log.debug("保存到数据库的消息：{}", JSONUtil.toJsonStr(saveMessage.getContent()));
        }
        else {
            log.error("保存消息失败：{}", JSONUtil.toJsonStr(saveMessage.getContent()));
            return;
        }

        // 如果这个消息是用户的，那么查询一下数据库看有没有上一条assistant的消息
        if (saveMessage.getType().equals("user")) {
            log.debug("userId: {}, this is user message, get last assistant message", creatorId);
            String lastAssistant = messageService.getLastAssistantMessage(creatorId, saveMessage.getSessionId());
            log.debug("lastAssistant: {}", lastAssistant);
            if (StrUtil.isNotEmpty(lastAssistant)) {
                log.info("userId: {}, lastAssistant not null, start analysis", creatorId);
                // 开始分析
                responseAnalysisService.analysis(creatorId, lastAssistant, saveMessage.getContent());
            }
        }

    }

    @Override
    public List<Message> get(String conversationId) {
        //获取最新lastN条数据
        List<Message> aiMessages = new ArrayList<>();
        List<com.dragon.english_practice_back.entity.Message> dbMessages = messageMapper.getLastNMessages(Integer.parseInt(conversationId), 10);

        for (com.dragon.english_practice_back.entity.Message dbMessage : dbMessages) {
            if (dbMessage.getMessageType().equals(MessageType.USER))aiMessages.add(new UserMessage(dbMessage.getContent()));
            if (dbMessage.getMessageType().equals(MessageType.ASSISTANT))aiMessages.add(new AssistantMessage(dbMessage.getText()));

        }
        return aiMessages;
    }

    @Override
    public void clear(String conversationId) {

    }
}
